let http = require('http');//跨域有关
let fs = require('fs');//输入输出流
let url =require('url');
// let querystring = require('querystring');//解析post之类的参数
let sliders = require(`./sliders`);//轮播图

function read(cb,wj='./books.json'){
  fs.readFile(wj,'utf8',function(err,data){//输出
    if(err || data.length === 0){
      cb([]);
    }else{
      cb(JSON.parse(data));
    }
  })
}
function write(data,cd,wj='./books.json'){//data输入的东西，cd回调函数
  fs.writeFile(wj,JSON.stringify(data),cd);//输入流
}

http.createServer((req,res)=>{
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
  res.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.setHeader("X-Powered-By",' 3.2.1')
  function reqData(fn){
    let pdata = '';
    req.on('data',function(chunk){
      pdata+=chunk;
    })
    req.on('end',function(){
      pdata = JSON.parse(pdata);
      // pdata = decodeURI(pdata);
      // console.log(pdata);
      // pdata = querystring.parse(pdata);
      // console.log(pdata);
      fn(pdata);
    })
  }
  //更改个人信息
  function setMy(){
    reqData(function(data){
      let pdata = data;
      read(function(data){
        let index = data.findIndex((val)=>val.id == pdata.id);
        if(index == -1){
          res.end('没有此人');
          return;
        }
        for(let key in pdata) {
          data[index][key] = pdata[key];
        }
        write(data,function(){
          res.end('true');
        },'./my.json');
      },'./my.json')
    });
  }

  if(req.method=="OPTIONS")return res.end();/*让options请求快速返回*/
  //true把url转化成对象,query参数对象
  let {pathname,query} = url.parse(req.url,true);//
  if(pathname==="/sliders"){
    res.setHeader('Content-Type','application/json;charset=utf8');
    return res.end(JSON.stringify(sliders));
  }
  if(pathname==='/hot'){
    read(function (books){
      let hot = books.reverse().slice(0,6);//颠倒，只拿6个
      res.setHeader('Content-Type','application/json;charset=utf8');
      res.end(JSON.stringify(hot));//不能对象
    });
    return
  }
  //猜你喜欢
  if(pathname==='/live'){
    read(function(live){
      let id = query.id;
      let arr = [];
      let i,b;
      while(arr.length!=6&&live.length>7){
        b = false;
        i = Math.round(Math.random()*(live.length-2))+1;
        if(live[i].bookId!=id){
          for(let j = 0;j<arr.length;j++){
            if(live[i].bookId==arr[j].bookId){
              b=true;
              break;
            }
          }
          if(b){
            continue;
          }
          arr.push(live[i]);
        }
      }
      res.setHeader('Content-Type','application/json;charset=utf8');
      res.end(JSON.stringify(arr));
    })
    return;
  }
  //下拉加载
  if(pathname==='/page'){
    read(function(data){
      let num = parseInt(query.num);
      let add =6;
      let arr = data.slice(num,num+add);
      if(arr.length===add){
        // res.setHeader('Content-Type', 'application/jsonsliders;charset=utf8');//下载
        res.setHeader('Content-Type','application/json;charset=utf8');
        res.end(JSON.stringify({data:arr,start:true}));
      }else{
        res.setHeader('Content-Type','application/json;charset=utf8');
        res.end(JSON.stringify({data:arr,start:false}));
      }
    })
    return;
  }
  if(pathname==='/book'){
    let id= parseInt(query.id);
    switch (req.method){//ajax的发送类型
      case 'GET':
        if(id){
          read(function(books){//信息
            books=books.find(data=>data.bookId===id);
            if(!books)books={};
            res.setHeader('Content-Type', 'application/jsonsliders;charset=utf8');
            res.end(JSON.stringify(books));
          })
        }else{
          read(function (books) {
            res.setHeader('Content-Type', 'application/json;charset=utf8');
            res.end(JSON.stringify(books.reverse().slice(0,8)));
          });
        }
        break;
      case 'POST':
        break;
      case 'PUT':
        break;
      case 'DELETE':
        read(function(books){
          books=books.filter(item=>item.bookId!==id);
          write(books,function(){
            res.end(JSON,stringify({}));
          })
        })
        break;
    }
    return
  }
  if(pathname==='/my'){
    let id = parseInt(query.id);
    switch(req.method){
      case 'GET':
        if(id){
          read(function(data){
            res.setHeader('Content-Type','application/json;charset=utf8');
            let my = data.find(function(val){
              return val.id==id;
            })
            if(!my)my={};
            res.end(JSON.stringify(my));
          },'./my.json')
        }
        break;
      case 'POST':
        break;
      case 'PUT':
        setMy();
        break;
      case 'DELETE':
        break;
    }
    return;
  }
}).listen(3000)//端口号3000


